﻿using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using BugzillaLoginSample.Proxy;
using CookComputing.XmlRpc;

namespace BugzillaLoginSample
{
   class Program
   {
      static void Main(string[] args)
      {
         try
         {
            // TODO: Don't forget to enable certification validation - never trust anyone
            // see http://codinghints.blogspot.com/2010/06/sooner-or-later-every-developer-has-to.html
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, errors) => (cert as X509Certificate2 ?? new X509Certificate2(cert)).Verify();

            var user = XmlRpcProxyGen.Create<IUserService>();
            user.Proxy = WebRequest.GetSystemWebProxy();

            var logIn = user.LogIn(new LogInRequest
            {
               User = ConfigurationManager.AppSettings["user"],
               Password = ConfigurationManager.AppSettings["password"]
            });

            Console.WriteLine("logged in as {0}", logIn.Id);

            user.CookieContainer.Add(user.ResponseCookies);

            var userInfo = user.Get(new UserInfoRequest
                                    {
                                       Ids = new[] { logIn.Id },
                                    });

            if (userInfo.UserInfos.Any())
            {
               var first = userInfo.UserInfos.First();
               Console.WriteLine("I'm {0}", first.RealName);
            }
            else
            {
               Console.WriteLine("No user");
            }

            user.LogOut();
         }
         catch (XmlRpcFaultException exception)
         {
            Console.WriteLine("{0}: {1}", exception.FaultCode, exception.FaultString);
         }
         Console.WriteLine("--- press <ANY> key ---");
         Console.ReadKey();
      }
   }
}
